package net.lesscoding.protocol;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import net.lesscoding.message.LoginRequestMessage;

/**
 * @author eleven
 * @date 2024/10/31 9:48
 * @apiNote
 */
public class MessageCodecTest {
    /**
     * 如果是无状态的handler就可以提取出公共变量，供给多个eventLoopGroup使用。
     * 但是 LengthFieldBasedFrameDecoder 这种需要区分每个channel的有状态的就不能抽离出来，否则就是线程不安全的。
     * 如果handler实现类上有 @Sharable {@link  io.netty.channel.ChannelHandler.Sharable} 注解就是可以共享使用的
     *
     */
    public static void main(String[] args) throws Exception {

        LoggingHandler loggingHandler = new LoggingHandler(LogLevel.DEBUG);
        EmbeddedChannel channel = new EmbeddedChannel(
                loggingHandler,
                new LengthFieldBasedFrameDecoder(1024, 16, 4, 0, 0),
                new MessageCodec()
        );
        // encode
        LoginRequestMessage loginRequestMessage = new LoginRequestMessage("username", "password");
        channel.writeOutbound(loginRequestMessage);
        // decode
        ByteBuf buffer = ByteBufAllocator.DEFAULT.buffer();
        new MessageCodec().encode(null, loginRequestMessage, buffer);
        ByteBuf slice1 = buffer.slice(0, 60);
        ByteBuf slice2 = buffer.slice(60, buffer.readableBytes() - 60);
        // channel.writeInbound之后会调用release,这就会导致slice1写完之后slice2直接报错了。需要retain
        buffer.retain();
        channel.writeInbound(slice1);
        channel.writeInbound(slice2);
    }
}
